﻿using System.Drawing;
using System.Globalization;
using System.Text.RegularExpressions;

namespace kmer.Web.Helper {
    /// <summary>
    /// 颜色处理
    /// </summary>
    public static class ColorHelper {
        /// <summary>
        /// #00AADD 转换为颜色（int）
        /// 如果没有转换成功会 返回  -1
        /// </summary>
        /// <param name="rgb"></param>
        /// <returns>如果没有转换成功会 返回  -1</returns>
        public static int ConvertColorToInt(string rgb) {
            var reg1 = new Regex("^#[0-9a-f]{6}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (reg1.IsMatch(rgb)) {
                var colorInt = 0;
                int.TryParse(rgb.Substring(1), NumberStyles.AllowHexSpecifier, new NumberFormatInfo(), out colorInt);
                return colorInt;
            }

            var reg2 = new Regex("^#[0-9a-f]{3}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (reg2.IsMatch(rgb)) {
                var colorInt = 0;
                int.TryParse($"{rgb.Substring(1,1)}{rgb.Substring(1,1)}{rgb.Substring(2,1)}{rgb.Substring(2,1)}{rgb.Substring(3,1)}{rgb.Substring(3,1)}", NumberStyles.AllowHexSpecifier, new NumberFormatInfo(), out colorInt);
                return colorInt;
            }
            
            return -1;
        }
        /// <summary>
        /// 颜色（整形）转 #FF01DE
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static string IntColorToWebStyle(int color){
            return $"#{color:X6}";
        }
        /// <summary>
        /// 颜色转 #FF01DE
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static string ToWebStyleColor(this Color color){
            return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
        }
    }

}
